package com.webchat.chat.web.socketio;

import com.webchat.chat.core.baseEntity.Result;
import com.webchat.chat.core.baseEntity.ResultGenerator;
import com.webchat.chat.core.enums.FileType;
import com.webchat.chat.core.exception.ServiceException;
import com.webchat.chat.core.tools.ChatConstant;
import com.webchat.chat.core.tools.FileUtil;
import com.webchat.chat.core.tools.ShiroUtil;
import com.webchat.chat.model.FileUploadRecord;
import com.webchat.chat.service.FileUploadRecordService;
import com.webchat.chat.web.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
 * Created by Owner on 2018/7/11.
 */
@RestController
@RequestMapping(ChatConstant.CONTROLLER_ROOT_PATH + "/common/file")
public class FileController extends BaseController {

    @Value("${chat.upload.file.root.path}")
    private String fileRootPath;

    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    @Resource
    private FileUploadRecordService fileUploadRecordService;

    /**
     * 文件上传
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file, HttpServletRequest request) {
        String tenantCode = ShiroUtil.getTenantCode();
        String userName = ShiroUtil.getUserName();
        if(StringUtils.isBlank(tenantCode) || StringUtils.isBlank(userName)){
            tenantCode = request.getParameter("tenantCode");
            userName = request.getParameter("userName");
        }
        if(StringUtils.isBlank(tenantCode) || StringUtils.isBlank(userName)){
            return ResultGenerator.genFailResult("缺少必要参数：tenantCode|userName");
        }
        String path = FileUtil.uploadFile(file, fileRootPath, tenantCode, userName);
        if(StringUtils.isBlank(path)){
            return ResultGenerator.genFailResult("缺少必要参数：tenantCode|userName");
        }
        FileUploadRecord fileUploadRecord = new FileUploadRecord();
        fileUploadRecord.setSourceUserName(userName);
        fileUploadRecord.setTenantCode(tenantCode);
        fileUploadRecord.setPath(path);
        fileUploadRecord.setCreatedBy(userName);
        fileUploadRecord.setCreatedDate(new Date());
        fileUploadRecordService.save(fileUploadRecord);
        return ResultGenerator.genSuccessResult(fileUploadRecord.getId());
    }

    @RequestMapping(value = "/down", method = RequestMethod.GET)
    public void down(String fileId, HttpServletResponse response){
        if(StringUtils.isBlank(fileId)){
            return;
        }

        FileUploadRecord fileUploadRecord = fileUploadRecordService.findById(fileId);
        if(fileUploadRecord == null){
            return;
        }
        String path = fileUploadRecord.getPath();
        if(StringUtils.isBlank(path)){
            return;
        }
        File file = new File(path);
        if(!file.exists()){
            return;
        }
        String name = file.getName();
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + name);

        //打开本地文件流
        InputStream inputStream = null;
        OutputStream os = null;
        try {
            inputStream = new FileInputStream(file);
            //激活下载操作
            os = response.getOutputStream();
            //循环写入输出流
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (FileNotFoundException e) {
            log.error("[{}]文件下载失败。错误原因：文件未找到", name);
            throw new ServiceException(name + "文件下载失败。错误原因：文件未找到");
        } catch (IOException e) {
            log.error("[{}]文件下载失败。错误原因：IO异常", name);
            throw new ServiceException(name + "文件下载失败。错误原因：IO异常");
        }finally {
            // 这里主要关闭。
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 获取文件类型
     * @return
     */
    @PostMapping("/getFileEnums")
    public Result getFileEnums(){
        FileType[] values = FileType.values();
        return ResultGenerator.genSuccessResult(values);
    }
}
